//
//  Emitterable.swift
//  RKTemplate
//
//  Created by zhaoke on 2023/9/25.
//

import Foundation
import UIKit

protocol Emitterable { }
extension Emitterable where Self : UIViewController {
    func startEmittering(_ point : CGPoint) {
        let emitter = CAEmitterLayer()  // 创建发射器
        emitter.emitterPosition = point  // 设置发射器位置
        emitter.preservesDepth = true  // 开启三维效果
        var cells = [CAEmitterCell]()
        for i in 0..<10 {
            let cell = CAEmitterCell()  // 创建粒子cell
            cell.velocity = 150  // 设置粒子速度
            cell.velocityRange = 20 // 设置粒子范围
            cell.scale = 0.7  // 设置粒子大小
            cell.scaleRange = 0.3
            cell.emissionLongitude = CGFloat(-(Double.pi / 2))  // 设置粒子方向
            cell.emissionLatitude = CGFloat((Double.pi / 2) / 6)
            cell.emissionRange = CGFloat((Double.pi / 2) / 4)
            cell.lifetime = 5  //粒子存活时间
            cell.lifetimeRange = 1.5
            cell.spin = CGFloat(Double.pi / 2)  // 设置粒子旋转
            cell.spinRange = CGFloat((Double.pi / 2) / 2)
            cell.birthRate = 2  // 设置粒子每秒弹出的个数
            cell.contents = UIImage(named: "good\(i)_30x30_")?.cgImage
            cells.append(cell)
        }
        emitter.emitterCells = cells
        view.layer.addSublayer(emitter)
    }
    func stopEmittering() {
        view.layer.sublayers?.filter({ $0.isKind(of: CAEmitterLayer.self) }).first?.removeFromSuperlayer()
    }
}

